package com.executor.gateway.controller;

import com.executor.gateway.service.MetricsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

/**
 * 监控控制器
 * 提供网关监控指标的REST API
 * 
 * @author miaoguoxin
 * @date 2024/01/01
 */
@RestController
@RequestMapping("/monitoring")
@Slf4j
public class MonitoringController {

    @Autowired
    private MetricsService metricsService;

    /**
     * 获取API统计信息
     */
    @GetMapping("/api/{apiPath}/statistics")
    public ResponseEntity<Object> getApiStatistics(
            @PathVariable String apiPath,
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime) {
        
        try {
            LocalDateTime start = startTime != null ? 
                    LocalDateTime.parse(startTime, DateTimeFormatter.ISO_LOCAL_DATE_TIME) : 
                    LocalDateTime.now().minusDays(1);
            
            LocalDateTime end = endTime != null ? 
                    LocalDateTime.parse(endTime, DateTimeFormatter.ISO_LOCAL_DATE_TIME) : 
                    LocalDateTime.now();

            Object statistics = metricsService.getApiStatistics(apiPath, start, end);
            return ResponseEntity.ok(statistics);
        } catch (Exception e) {
            log.error("Error getting API statistics for path: " + apiPath, e);
            Map<String, String> error = new HashMap<>();
            error.put("error", "Failed to get API statistics: " + e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }

    /**
     * 获取服务统计信息
     */
    @GetMapping("/service/{serviceId}/statistics")
    public ResponseEntity<Object> getServiceStatistics(
            @PathVariable String serviceId,
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime) {
        
        try {
            LocalDateTime start = startTime != null ? 
                    LocalDateTime.parse(startTime, DateTimeFormatter.ISO_LOCAL_DATE_TIME) : 
                    LocalDateTime.now().minusDays(1);
            
            LocalDateTime end = endTime != null ? 
                    LocalDateTime.parse(endTime, DateTimeFormatter.ISO_LOCAL_DATE_TIME) : 
                    LocalDateTime.now();

            Object statistics = metricsService.getServiceStatistics(serviceId, start, end);
            return ResponseEntity.ok(statistics);
        } catch (Exception e) {
            log.error("Error getting service statistics for service: " + serviceId, e);
            Map<String, String> error = new HashMap<>();
            error.put("error", "Failed to get service statistics: " + e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }

    /**
     * 获取网关整体健康状态
     */
    @GetMapping("/health")
    public ResponseEntity<Map<String, Object>> getGatewayHealth() {
        Map<String, Object> health = new HashMap<>();
        try {
            health.put("status", "UP");
            health.put("timestamp", LocalDateTime.now().toString());
            health.put("version", "1.0.0");
            
            // 可以添加更多健康检查逻辑
            // 例如：检查Redis连接、数据库连接等
            
            return ResponseEntity.ok(health);
        } catch (Exception e) {
            log.error("Error getting gateway health", e);
            health.put("status", "DOWN");
            health.put("error", e.getMessage());
            return ResponseEntity.status(503).body(health);
        }
    }

    /**
     * 手动触发指标持久化
     */
    @PostMapping("/metrics/persist")
    public ResponseEntity<Map<String, String>> persistMetrics() {
        try {
            metricsService.save2Db();
            Map<String, String> result = new HashMap<>();
            result.put("message", "Metrics persisted successfully");
            result.put("timestamp", LocalDateTime.now().toString());
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("Error persisting metrics", e);
            Map<String, String> error = new HashMap<>();
            error.put("error", "Failed to persist metrics: " + e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }

    /**
     * 获取实时指标概览
     */
    @GetMapping("/overview")
    public ResponseEntity<Map<String, Object>> getMetricsOverview() {
        Map<String, Object> overview = new HashMap<>();
        try {
            // 这里可以实现获取实时指标概览的逻辑
            overview.put("timestamp", LocalDateTime.now().toString());
            overview.put("message", "Metrics overview endpoint - implementation needed");
            
            return ResponseEntity.ok(overview);
        } catch (Exception e) {
            log.error("Error getting metrics overview", e);
            Map<String, String> error = new HashMap<>();
            error.put("error", "Failed to get metrics overview: " + e.getMessage());
            overview.put("error", error);
            return ResponseEntity.badRequest().body(overview);
        }
    }
}